<template>
<div>
  <n-drawer v-model:show="isShow" :width="500" placement="right" @update:show="clearForm">
    <n-drawer-content :title="drawerTitle" closable>
      <n-form
        :model="userForm"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="100"
      >
        <n-form-item label="登录账号" path="username">
           <n-input v-model:value="userForm.username"  placeholder="请输入登录账号"/>
        </n-form-item>
        <n-form-item label="真实姓名" path="realName">
          <n-input v-model:value="userForm.realName"  placeholder="请输入真实姓名"/>
        </n-form-item>
        <n-form-item label="头像" path="imageList">
          <BasicUpload
            :action="`${uploadUrl}/upload/uploadImg`"
            :headers="uploadHeaders"
            name="file"
            :width="100"
            :height="100"
            @uploadChange="uploadChange"
            v-model:value="userForm.imageList"
          />
        </n-form-item>
        <n-form-item label="手机号码" path="phone">
          <n-input v-model:value="userForm.phone"  placeholder="请输入手机号码" maxlength="11" minlength="11" :show-count="true"/>
        </n-form-item>
        <div v-if="!userForm.id">
          <n-form-item label="密码" path="password">
            <n-input type="password" v-model:value="userForm.password" showPasswordOn="click" placeholder="请输入密码" :maxlength="8"/>
          </n-form-item>
          <n-form-item label="确认密码" path="confirmPass">
            <n-input type="password" v-model:value="userForm.confirmPass" showPasswordOn="click" placeholder="请再次密码" :maxlength="8"/>
          </n-form-item>
        </div>
        <n-form-item label="邮箱" path="email">
          <n-input v-model:value="userForm.email"  placeholder="请输入邮箱"/>
        </n-form-item>
        <n-form-item label="角色" path="roleList">
          <n-select v-model:value="userForm.roleList" placeholder="请选择角色" multiple :options="roleListData" />
        </n-form-item>
        <n-form-item label="部门" path="deptId">
          <n-tree-select :options="deptTreeData" v-model:value="userForm.deptId"/>
        </n-form-item>
        <n-form-item label="岗位" path="jobId">
          <n-select v-model:value="userForm.jobId" placeholder="请选择岗位" :options="jobList" />
        </n-form-item>
        <n-form-item label="简介" path="remark">
          <n-input v-model:value="userForm.remark" type="textarea" placeholder="请输入个人简介" />
        </n-form-item>
        </n-form>
      <template #footer>
        <n-space>
          <n-button type="primary" :loading="submitLoading" @click="submitForm">提交</n-button>
          <n-button @click="handleResetForm">关闭</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</div>
</template>

<script lang="ts">
import {defineComponent,ref,reactive,unref,onMounted} from 'vue'
import { useUserStore } from '@/store/modules/user';
import {useMessage} from 'naive-ui'
import { BasicUpload } from '@/components/Upload';
import { useGlobSetting } from '@/hooks/setting';
import {checkUsername,checkMobile,saveUser,updateUser} from "@/api/system/user";
import {getJobList} from "@/api/system/job";
import {roleList} from "@/api/system/role";
import {getDeptTreeData} from "@/api/system/dept";

export default defineComponent( {
  name: "UserForm",
  components:{
    BasicUpload
  },
  props:{
    drawerTitle:{
      type:String
    }
  },
  setup(props,context){
    const userStore = useUserStore();
    const message=useMessage();
    const isShow=ref(false);
    const userForm=ref({});
    const formRef=ref(null);
    const globSetting = useGlobSetting();
    const { uploadUrl } = globSetting;
    const submitLoading=ref(false);
    const oldUsername=ref('');
    const oldMobile=ref('');
    const roleListData=ref([]);
    const deptTreeData=ref([]);
    const jobList=ref([]);
    const uploadHeaders = reactive({
      Authorization: "Bearer "+userStore.token,
    });
    const rules={
      username:{
        required:true,trigger:'blur',
        validator: (rule, value) => {
          return new Promise((resolve, reject) => {
            if(value==null){
              reject(Error('请输入登录账号'))
            }else{
              checkUsername({username:value,oldUsername:oldUsername.value}).then(res=>{
                if(res){
                  reject(Error('登录账号已存在'))
                }else{
                  resolve()
                }
              })
            }
          })
        }
      },
      realName:{required:true,trigger:'blur',message:'请输入真实姓名'},
      imageList:{type:'array',required:true,trigger:'change',message:'请上传头像'},
      email:{required:true,trigger:'blur',
        validator:(rule,value)=>{
          return new Promise((resolve, reject) => {
          const regEmail=/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if(value==null) {
              reject(Error('请输入邮箱'))
            }else if(!regEmail.test(value)){
              reject(Error('邮箱格式不正确'))
            }else{
              resolve()
            }
        })
        }
      },
      phone:{required:true,trigger:'blur',
        validator: (rule, value) => {
          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
          return new Promise((resolve, reject) => {
            if(value==null){
              reject(Error('请输入手机号码'))
            }else if(!reg.test(value)){
              reject(Error('请输入正确的手机号码'))
            }else{
              checkMobile({mobile:value,oldMobile:oldMobile.value}).then(res=>{
                if(res){
                  reject(Error('手机号码已存在'))
                }else{
                  resolve()
                }
              })
            }
          })
        }
      },
      password:{
        required:true,trigger:'blur',
        validator:(rule, value)=>{
          return new Promise((resolve, reject) => {
            if(value==null){
              reject(Error('请输入密码'))
            } else{
              if (value.length < 6) {
                reject(new Error('密码长度不得小于6位'));
              } else {
                resolve();
              }
            }
          })
        }
      },
      confirmPass:{
        required:true,trigger:'blur',
        validator:(rule, value)=>{
          return new Promise((resolve, reject) => {
            if(value==null){
              reject(Error('请再次输入密码'))
            } else{
              if (value.length < 6) {
                reject(new Error('密码长度不得小于6位'));
              } else if(userForm.value.password!=value) {
                reject(new Error("两次输入的密码不一致"));
              }else{
                resolve()
              }
            }
          })
        }
      },
      roleList:{type:'array',required:true,message:'请选择角色',trigger:'blur'},
      deptId:{required:true,message:'请选择部门',trigger:'blur'},
      jobId:{required:true,message:'请选择岗位',trigger:'blur'}
    }
    function clearForm() {
      Object.keys(userForm.value).forEach((key)=>{
        if(key!=='id'&&key!=='imageList'){
          userForm.value[key]='';
        }
        userForm.value['imageList']=[]
      })
      submitLoading.value=false;
    }
    function uploadChange(list: string[]) {
      if(list.length>0){
        userForm.value.imageList= unref(list);
      }else{
        userForm.value.imageList=[]
      }
    }
    function handleResetForm() {
      isShow.value=false;
      Object.keys(userForm.value).forEach((key)=>{
        if(key!=='id'&&key!=='imageList'){
          userForm.value[key]=null;
        }
        userForm.value['imageList']=[]
      })
      submitLoading.value=false;
    }
    function submitForm(){
      formRef.value.validate((errors:boolean)=>{
        if(!errors){
          submitLoading.value=true;
          userForm.value.avatar=userForm.value.imageList[0];
          let obj;
          if(userForm.value.id!=null&&typeof(userForm.value.id)!='undefined'){
            obj=updateUser(userForm.value);
          }else{
            obj=saveUser(userForm.value);
          }
          obj.then(res=>{
            if(res){
              message.success('提交成功');
              isShow.value=false;
              submitLoading.value=false;
              clearForm();
              context.emit('on-success');
            }
          })
        }else{
          message.error('提交失败')
        }
      })
    }
    onMounted(async ()=>{
      let roleData=await roleList();
      roleListData.value= roleData.map((data)=>{
        return {
          value:data.id,
          label:data.roleName
        }
      })
      let data= await getDeptTreeData();
      deptTreeData.value=data;
      let jobData=await getJobList();
      jobList.value= jobData.map((data)=>{
        return {
          value:data.id,
          label:data.jobName
        }
      })
    })
    return {
      isShow,
      clearForm,
      userForm,
      formRef,
      rules,
      submitLoading,
      uploadUrl,
      handleResetForm,
      submitForm,
      uploadHeaders,
      oldMobile,
      oldUsername,
      uploadChange,
      roleListData,
      deptTreeData,
      jobList
    }
  }
})
</script>

<style scoped>

</style>
